<script setup lang="ts">
import type { ConsultIllness, Image } from '@/types/consult'
import { ref, computed, onMounted } from 'vue'
import { IllnessTime } from '@/enums'
import type {
  UploaderAfterRead,
  UploaderFileListItem
} from 'vant/lib/uploader/types'
import { uploadImage } from '@/services/consult'
import { showConfirmDialog, showToast } from 'vant'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'
// 表单对象
const form = ref<ConsultIllness>({
  // 默认放个数组, 不然之后没法往里推
  pictures: []
})
// 表单内按钮选项配置
const timeOptions = [
  { label: '一周内', value: IllnessTime.Week },
  { label: '一月内', value: IllnessTime.Month },
  { label: '半年内', value: IllnessTime.HalfYear },
  { label: '半年以上', value: IllnessTime.More }
]

const flagOptions = [
  { label: '就诊过', value: 0 },
  { label: '没就诊过', value: 1 }
]

// 上传相关
// 双向绑定数据
const fileList = ref<Image[]>([])
const onAfterRead: UploaderAfterRead = async (item) => {
  // 读取文件以后
  // 根据组件库类型声明, 可以发现item有可能是图片, 或者图片组成的数组, 这里限制一下,每次只能一张
  if (Array.isArray(item)) return
  // 判断必须有文件,才继续往下走
  if (!item.file) return

  try {
    item.status = 'uploading'
    item.message = '上传中...'

    const res = await uploadImage(item.file)
    console.log(res.data.url)

    item.status = 'done'
    item.message = undefined

    // 上传完毕,在fileList 数组对象中记录当前这张图片的在线地址
    // 方便后面删除的时候用作标识, 清理 form.value.pictures里面的数据
    item.url = res.data.url
    // 上传完毕, 将数据放入到 form 表单 picture 里面去
    form.value.pictures?.push(res.data)
  } catch (err) {
    item.status = 'failed'
    item.message = '上传失败'
  }
}
const onDeleteImg = (item: UploaderFileListItem) => {
  // 删除图片
  console.log(item)
  form.value.pictures = form.value.pictures?.filter(
    (pic) => pic.url !== item.url
  )
}

// 下一步按钮相关
const store = useConsultStore()
const router = useRouter()
const next = () => {
  // 1. 检查数据
  if (disabled.value) return showToast('请先填写全部信息')
  // 保存数据
  store.setIllness(form.value)
  // 跳转页面
  router.push('/user/patient?isChange=1')
}
const disabled = computed(
  () =>
    !form.value.illnessDesc?.trim() ||
    form.value.illnessTime === undefined ||
    form.value.consultFlag === undefined
)

// 回显数据
onMounted(async () => {
  if (store.consult.illnessDesc) {
    await showConfirmDialog({
      title: '友情提示',
      message: '是否恢复之前填写的病情信息?',
      closeOnPopstate: false
    })
    const { illnessDesc, illnessTime, consultFlag, pictures } = store.consult
    form.value = { illnessDesc, illnessTime, consultFlag, pictures }
    fileList.value = pictures || []
  }
})
</script>

<template>
  <div class="consult-illness-page">
    <cp-nav-bar title="图文问诊" />
    <!-- 医生提示 -->
    <div class="illness-tip van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <div class="info">
        <p class="tit">在线医生</p>
        <p class="tip">
          请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
        </p>
        <p class="safe">
          <cp-icons name="consult-safe" /><span>内容仅医生可见</span>
        </p>
      </div>
    </div>
    <!-- 表单 -->
    <div class="illness-form">
      <van-field
        type="textarea"
        rows="3"
        placeholder="请详细描述您的病情，病情描述不能为空"
        v-model="form.illnessDesc"
      ></van-field>
      <div class="item">
        <p>本次患病多久了？</p>
        <cp-radio-btn :options="timeOptions" v-model="form.illnessTime" />
      </div>
      <div class="item">
        <p>此次病情是否去医院就诊过？</p>
        <cp-radio-btn :options="flagOptions" v-model="form.consultFlag" />
      </div>
      <!-- 上传组件 -->
      <div class="illness-img">
        <van-uploader
          :after-read="onAfterRead"
          @delete="onDeleteImg"
          v-model="fileList"
          upload-icon="photo-o"
          upload-text="上传图片"
          :max-count="9"
          :max-size="1 * 1024 * 1024"
        ></van-uploader>
        <p class="tip">上传内容仅医生可见,最多9张图,最大5MB</p>
      </div>
      <van-button :class="{ disabled }" @click="next" type="primary" block round
        >下一步</van-button
      >
    </div>
  </div>
</template>

<style lang="scss" scoped>
.consult-illness-page {
  padding-top: 46px;
}

.illness-tip {
  display: flex;
  padding: 15px;
  .img {
    width: 52px;
    height: 52px;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 10px;
  }
  .info {
    flex: 1;
    padding-left: 12px;
    .tit {
      font-size: 16px;
      margin-bottom: 5px;
    }
    .tip {
      padding: 12px;
      background: var(--cp-bg);
      color: var(--cp-text3);
      font-size: 13px;
      margin-bottom: 10px;
    }
    .safe {
      font-size: 10px;
      color: var(--cp-text3);
      display: flex;
      align-items: center;
      .cp-icon {
        font-size: 12px;
        margin-right: 2px;
      }
    }
  }
}

.illness-form {
  padding: 15px;
  .van-field {
    padding: 0;
    &::after {
      border-bottom: none;
    }
  }
  .item {
    > p {
      color: var(--cp-text3);
      padding: 15px 0;
    }
  }
}

.illness-img {
  padding-top: 16px;
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  .tip {
    font-size: 12px;
    color: var(--cp-tip);
  }
  ::v-deep() {
    .van-uploader {
      &__preview {
        &-delete {
          left: -6px;
          top: -6px;
          border-radius: 50%;
          background-color: var(--cp-primary);
          width: 20px;
          height: 20px;
          &-icon {
            transform: scale(0.9) translate(-22%, 22%);
          }
        }
        &-image {
          border-radius: 8px;
          overflow: hidden;
        }
      }
      &__upload {
        border-radius: 8px;
      }
      &__upload-icon {
        color: var(--cp-text3);
      }
    }
  }
}

.van-button {
  font-size: 16px;
  margin-bottom: 30px;
  &.disabled {
    opacity: 1;
    background: #fafafa;
    color: #d9dbde;
    border: #fafafa;
  }
}
</style>
